﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using BrokerBase.Lib.Product;
using NHibernate;

namespace BrokerBase.Lib.Tool
{
    public class ImportUtil
    {
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);

        private const int RATE_DATA_BEGIN_COLUMN = 4;

        private int maxCol;
        private int maxRow;

        public void ImportRate(string path,IProduct product)
        {
            Microsoft.Office.Interop.Excel.Application excelApp = null;
            try
            {
                excelApp = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel.Worksheet sheet = null;

                excelApp.Workbooks.Open(path);

                try
                {
                   

                    sheet = excelApp.Worksheets["固定费率表"];
                }
                catch
                {
                    //sheet = excelApp.Worksheets[1];
                    throw new Exception("没有找到[固定费率表]!");
                }

                Clear(product);

                ReadFactor(sheet, product);
                ReadRate(sheet, product);

                excelApp.Workbooks.Close();
                excelApp.Quit();


            }
            catch (Exception er)
            {

                throw er;
            }
            finally
            {
                KillExcel(excelApp);
            }
        }


         ///<summary>
         ///读取费率元素的类别
         ///</summary>
         ///<param name="sheet">工作表</param>
         ///<returns></returns>
        private void ReadFactor(Microsoft.Office.Interop.Excel.Worksheet sheet, IProduct product)
        {

            string value;

            int i = 0;
            int j = 0;

            //获取最大行和最大列
            maxCol = sheet.UsedRange.Columns.Count;
            maxRow = sheet.UsedRange.Rows.Count;

            product.MaxRateCol = maxCol - RATE_DATA_BEGIN_COLUMN + 1;

            IList<string> elemenStr = new List<string>();

            try
            {

                for (i = 1; i <= maxRow; i++)
                {
                    value = sheet.Cells[i, 3].value;
                    value = value==null?null:value.Trim();

                    if (string.IsNullOrEmpty(value))//空行
                    {
                        break;
                    }
                    else
                    {
                        //读取费率元素的数据
                        //IFixRateElement el = new FixRateElement();

                        IRateFactor crf = new RateFactor(product,RateFactorAxis.Col);
                        product.ColRateFactors.Add(crf);

                        crf.Name = value.Trim();
                        crf.ConverterInstance = ProductUtil.GetRateFactorConverter(crf.Name);

                        for (j = RATE_DATA_BEGIN_COLUMN; j <= maxCol; j++)
                        {

                            var tmp1 = sheet.Cells[i, j].value;
                            value = (tmp1 == null ? string.Empty : tmp1.ToString().Trim());
                            if (value.ToString()!= string.Empty)
                            {
                                crf.Items += crf.Items == null ? value : ";" + value;
                            }
                            else
                            {
                                //如果为空则取上一个项目
                                IList<string> tmp = crf.Items.Split(';');
                                crf.Items += ";" + tmp[tmp.Count - 1];
                            }
                        } 
                    }
                }

                object key1 = sheet.Cells[product.ColRateFactors.Count, 1].value;

                IRateFactor rrf1 = new RateFactor(product, RateFactorAxis.Row);

                if (key1 == null || string.IsNullOrEmpty(key1.ToString().Trim()))
                    rrf1.Name = RateFactor.RowRateFactorDefaultName1;
                else
                    rrf1.Name = key1.ToString().Trim();

                rrf1.ConverterInstance = ProductUtil.GetRateFactorConverter(rrf1.Name);
                product.RowRateFactors.Add(rrf1);

                object key2 = sheet.Cells[product.ColRateFactors.Count, 2].value;

                IRateFactor rrf2 = new RateFactor(product, RateFactorAxis.Row);
                if (key2 == null || string.IsNullOrEmpty(key2.ToString().Trim()))
                    rrf2.Name = RateFactor.RowRateFactorDefaultName2;
                else
                    rrf2.Name = key2.ToString().Trim();

                rrf2.ConverterInstance = ProductUtil.GetRateFactorConverter(rrf2.Name);
                product.RowRateFactors.Add(rrf2);

                int dataBeginRow=product.ColRateFactors.Count+1;

                product.MaxRateRow = maxRow - dataBeginRow + 1;

                //for (int row = dataBeginRow; row <= maxRow; row++)
                //{

                //    var rowFactorItem1 = sheet.Cells[row, 1].value;
                //    var rowFactorItem2 = sheet.Cells[row, 2].value;

                //    //rrf1=product.RowRateFactors[0];
                //    //rrf2 = product.RowRateFactors[1];

                //    rrf1.Items += rrf1.Items == null ? rowFactorItem1 : ";" + rowFactorItem1;
                //    rrf2.Items += rrf2.Items == null ? rowFactorItem2 : ";" + rowFactorItem2;

                //}
            }
            catch (Exception ex)
            {
                Clear(product);
                throw new Exception(string.Format("读取费率因子时发生错误,行{0},列{1},请检查费率表格式是否正确.",i,j),ex);
            }
        }

        private void ReadRate(Microsoft.Office.Interop.Excel.Worksheet sheet, IProduct product)
        {
            //IList<IFixRateData> rates = new List<IFixRateData>();

            //获取最大行和最大列
            int maxCol = sheet.UsedRange.Columns.Count;
            int maxRow = sheet.UsedRange.Rows.Count;

            int dataBeginRow = product.ColRateFactors.Count + 1;

            int wrapCount = maxCol / RateRow.MAX_COLUMN + (maxCol % RateRow.MAX_COLUMN > 0 ? 1 : 0);

            try
            {
               

                for (int row = dataBeginRow; row <= maxRow; row++)
                {

                    //Debug.Assert(i != 46);
                    //读取每行的数据
                    //读取开始时间和结束时
                    string key1 = null;
                    string key2 = null;

                    key1 = sheet.Cells[row, 1].value == null ? string.Empty : sheet.Cells[row, 1].value.ToString();
                    key2 = sheet.Cells[row, 2].value == null ? string.Empty : sheet.Cells[row, 2].value.ToString();

                    key1 = key1.Trim();
                    key2 = key2.Trim();


                    product.RowRateFactors[0].Items += key1 + ";";
                    product.RowRateFactors[1].Items += key2 + ";";


                    for (int index = 0; index < wrapCount; index++)
                    {
                        IRateRow rateRow = new RateRow(product);

                        product.RateRows.Add(rateRow);

                        rateRow.WrapIndex = index;
                        rateRow.Key1 = key1;
                        rateRow.Key2 = key2;

                        for (int col = 0; col < RateRow.MAX_COLUMN; col++)
                        {
                            int x = index * RateRow.MAX_COLUMN + col;

                            if (x < maxCol)
                            {
                                object v1 = sheet.Cells[row, x + RATE_DATA_BEGIN_COLUMN].value;
                                double? v2 = 0;

                                try
                                {
                                    //v2=v1==null?null:(double?)double.Parse(v1.ToString());

                                    if (v1 == null)
                                        v2 = null;
                                    else if (string.IsNullOrEmpty(v1.ToString().Trim()))
                                        v2 = null;
                                    else
                                        v2 = (double?)double.Parse(v1.ToString().Trim());

                                }catch(Exception ex)
                                {
                                    throw new Exception(string.Format("无法转化为数值，第{0}行，第{1}列",row,col+RATE_DATA_BEGIN_COLUMN)+Environment.NewLine+ex.Message);
                                }

                                rateRow.Rates[col] = v2;
                            }
                            else
                            {
                                break;//超出范围，退出循环
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }           
       }

        private void Clear(IProduct product)
        {
            product.ColRateFactors.Clear();
            product.RowRateFactors.Clear();
            product.RateRows.Clear();
        }

        public static void KillExcel(Microsoft.Office.Interop.Excel.Application excel) 
        { 
            IntPtr t=new IntPtr(excel.Hwnd); //得到这个句柄，具体作用是得到这块内存入口 
            int k= 0; 
            GetWindowThreadProcessId(t,out k); //得到本进程唯一标志k 
            System.Diagnostics.Process p=System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用 
            p.Kill(); //关闭进程k 
        }

    }
}
